package com.zangchat.controller;


import com.alibaba.fastjson.JSONObject;
import com.common.core.controller.BaseController;
import com.common.core.domain.AjaxResult;
import com.zangchat.domain.ChatUsers;
import com.zangchat.domain.mongoBean.MTrendsBean;
import com.zangchat.service.IChatUsersService;
import com.zangchat.service.IMongoDbService;
import com.zangchat.utils.NetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 用户Controller
 * 
 * @author wudi
 * @date 2020-07-06
 */
@RestController
@RequestMapping("/zangchat/users")
public class ChatUsersController extends BaseController
{

    @Autowired
    private IChatUsersService chatUsersService;

    /**
     *
     * 用户同意授权，获取code
     */
    @RequestMapping("/authorize")
    @ResponseBody
//    @IgnoreToken
    public AjaxResult authorize(HttpServletRequest request, HttpServletResponse response) {
        return chatUsersService.getUrlForoauth(request);
    }

    /**
     * 微信登录
     * @param request
     * @param response
     * @param model
     * @throws Exception
     */
    @RequestMapping("/weixinLogin")
    @ResponseBody
//    @IgnoreToken
//    @IgnoreSign
    public void weixinLogin(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        // 用户同意授权后，能获取到code
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到code的值
        String code = codes[0];//code
        //String[] states = params.get("state");
        //String state = states[0];//state

        System.out.println("****************code:"+code);
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
            requestUrl = requestUrl.replace("APPID", "wx4e9d2de9854c0b7e");
            requestUrl = requestUrl.replace("SECRET", "1fc719727e108b389b50a3c83528beea");
            requestUrl = requestUrl.replace("CODE", code);
            // 获取网页授权凭证
            String s = NetUtil.get(requestUrl);
            System.out.println(s);
            JSONObject jsonObject = JSONObject.parseObject(s);
//            JSONObject jsonObject = JSON.parseObject(s);
//            System.out.println("***************jsonObject**************"+jsonObject);
            String openid = jsonObject.getString("openid");
            System.out.println("***************openid**************"+openid);
            String access_token = jsonObject.getString("access_token");
            System.out.println("***************access_token**************"+access_token);
            // 获取网页授权access_token
//            Oauth2Token oauth2Token = getOauth2AccessToken(PayConstant.WX_APP_IDG, PayConstant.API_KEYG, code);
//            System.out.println("***********************************oauth2Token信息："+oauth2Token);
//            // 网页授权接口访问凭证
//            String accessToken = oauth2Token.getAccessToken();
//            // 用户标识
//            String openId = oauth2Token.getOpenId();
            /**   看参数scope 获取微信用户信息   */
//            SNSUserInfo snsUserInfo = getSNSUserInfo(accessToken, openId);
//            System.out.println("用户信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + snsUserInfo);
//            System.out.println("***********************************用户信息unionId："+snsUserInfo.getUnionid()+"***:"+snsUserInfo.getNickname());
            // 设置要传递的参数

//            model.addAttribute("openId",openid);

//            String url = "http://rbzh5test.56365.cc/?openId="+openid;

//            response.sendRedirect(url);
        }
    }
    @PostMapping("/getUserData")
    @ResponseBody
    public String getUserData(String access_token,String openid,HttpServletRequest request){
        // 用户同意授权后，能获取到code
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到code的值
        String code = codes[0];//code

        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", access_token);
        requestUrl = requestUrl.replace("OPENID", openid);
        String s = NetUtil.get(requestUrl);
        JSONObject jsonObject = JSONObject.parseObject(s);

//        AjaxResult ajaxResult=qlwShopUsersService.vxOauthLogin(jsonObject,request);

        return s;
    }

    @PostMapping("/checkAccessToken")
    @ResponseBody
    public String checkAccessToken(String access_token,String openid){

        String requestUrl = "https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;
        String s = NetUtil.get(requestUrl);
        System.out.println(s);
        return s;
    }

    /**
     * 直接注册
     *
     * @param userPhone       手机号
     * @param password        密码
     * @param confirmPassword 确认密码
     * @param smsCode         短信验证码
     * @param invite          推荐人手机号
     */
    @RequestMapping("/register")
    public AjaxResult register (@ModelAttribute("userPhone") String userPhone,
                                @ModelAttribute("password") String password,
                                @ModelAttribute("confirmPassword") String confirmPassword,
                                @ModelAttribute("smsCode") String smsCode,
                                @ModelAttribute("invite") String invite){
        return   chatUsersService.register(userPhone,  password,  confirmPassword,  smsCode,  invite);
    }
    /**
     * 用户登录
     * @param userPhone 手机号
     * @param password 密码
     * @param derviceId 设备唯一识别码
     * @param longitude 经度
     * @param latitude 纬度
     * @return
     */
    @RequestMapping("/login")
    public AjaxResult login(@ModelAttribute("userPhone") String userPhone,
                            @ModelAttribute("password") String password,
                            @ModelAttribute("derviceId") String derviceId,
                            @ModelAttribute("longitude") double longitude,
                            @ModelAttribute("latitude") double latitude){
        return   chatUsersService.login(userPhone,password,derviceId,longitude,latitude);
    }

    /**
     * 校验手机号是否已经注册
     *
     * @param userPhone       手机号
     */
    @PostMapping("/checkedUserPhone")
    public AjaxResult checkedUserPhone ( String userPhone){
        return   chatUsersService.checkedUserPhone(userPhone)!=null?AjaxResult.success(1):AjaxResult.success(0);
    }

    /**
     * 修改密码
     * @param userPhone
     * @param oldPassword
     * @param newPassword
     * @param confirmPassword
     * @return
     */
    @RequestMapping("/updatePassword")
    public AjaxResult updatePassword(@ModelAttribute("userPhone") String userPhone,
                                     @ModelAttribute("password") String oldPassword,
                                     @ModelAttribute("newPassword") String newPassword,
                                     @ModelAttribute("confirmPassword") String confirmPassword){
        return chatUsersService.updatePassword(userPhone,oldPassword,newPassword,confirmPassword);
    }


    /**
     * 忘记密码
     * @param userPhone
     * @param smsCode
     * @param newPassword
     * @param confirmPassword
     * @return
     */
    @RequestMapping("/forgetPassword")
    public AjaxResult forgetPassword (@ModelAttribute("userPhone") String userPhone,
                                      @ModelAttribute("smsCode") String smsCode,
                                      @ModelAttribute("newPassword") String newPassword,
                                      @ModelAttribute("confirmPassword") String confirmPassword,
                                      @ModelAttribute("type") String type){
        return chatUsersService.forgetPassword(userPhone,smsCode,newPassword,confirmPassword,type);
    }

    /**
     * 我的资料(用户基本信息，不包括认证)
     * @param userId
     * @return
     */
    @RequestMapping("/getUserDetail")
    public AjaxResult getUserDetail(@ModelAttribute("userId") Long userId){
        return chatUsersService.getUserDetail(userId);
    }

    /**
     * 注册之后第一步操作 完善个人信息 1
     * @param userId 用户id
     * @param sex 性别
     * @param userName 昵称
     * @param headImg 头像
     * @return
     */
    @RequestMapping("/supplement_one")
    public AjaxResult supplementOne(@ModelAttribute("userId") Long userId,
                                    @ModelAttribute("sex") Integer sex,
                                    @ModelAttribute("userName") String userName,
                                    @ModelAttribute("headImg")String headImg){

        return toAjax(chatUsersService.supplementOne(userId,sex,userName,headImg));
    }

    /**
     * 注册之后第二步操作 完善个人信息 1
     * @param userId 用户id
     * @param flagList 标签
     * @param cover 封面
     * @return
     */
    @RequestMapping("/supplement_two")
    public AjaxResult supplementTwo(@ModelAttribute("userId") Long userId,
                                    @ModelAttribute("flagList") String flagList,
                                    @ModelAttribute("cover")String cover){

        return chatUsersService.supplementTwo(userId,flagList,cover);
    }

}
